#include "service.h"
#include "z_logger.h"
#include "aiot_ra_api.h"
#include "aiot_ra_private.h"

static void _ra_event_cb(void *handle, const aiot_ra_event_t *event, void *userdata) {
    switch (event->type) {
        case AIOT_RA_EVT_CONNECT:
            log_trace("connect %s", event->tunnel_id);
            break;
        case AIOT_RA_EVT_DISCONNECT:
            log_trace("disconnect %s", event->tunnel_id);
            break;
        case AIOT_RA_EVT_OPEN_WEBSOCKET:
            log_trace("open websocket %s", event->tunnel_id);
            break;
        case AIOT_RA_EVT_CLOSE_WEBSOCKET:
            log_trace("close websocket %s", event->tunnel_id);
            break;
    }
}

void *ra_service_init(aliot_service_args_t *args) {
    void *ra_handle = aiot_ra_init();

    aiot_ra_setopt(ra_handle, AIOT_RAOPT_MQTT_HANDLE, args->mqtt_handle);
    aiot_ra_setopt(ra_handle, AIOT_RAOPT_NETWORK_CRED, args->cred);
    aiot_ra_setopt(ra_handle, AIOT_RAOPT_EVENT_HANDLER, _ra_event_cb);
    aiot_ra_service_t ssh_port = {.type = "_SSH", .ip = "127.0.0.1", .port = 22};
    aiot_ra_setopt(ra_handle, AIOT_RAOPT_ADD_SERVICE, &ssh_port);

    return ra_handle;
}

static void _ra_service_fini(void **handle) {
    aiot_ra_deinit(handle);
}

static aliot_service_t _ra_service = {
        .name = "ra",
        .init = ra_service_init,
        .fini = _ra_service_fini,
        .start = aiot_ra_start,
        .stop = aiot_ra_stop,
};

aliot_service_t *ra_service_get() {
    return &_ra_service;
}